package login;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utility.connections;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String user,pwd;
    
    private HttpSession session;
    private int account;
    
    public Login() {
        super();
    }
    
    public void init(ServletConfig sc)
    {
    	try {
			super.init(sc);
		} catch (ServletException e) {
			e.printStackTrace();
		}
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		user = request.getParameter("txtuser");
		pwd  = request.getParameter("txtpwd");
		System.out.println("user: "+user+", pwd:"+pwd);
		try {
			String qry = "select a.username,a.tipologia as tipologia,p.* from account a, personale p where username = '" + user
					   + "' and password = '" + pwd + "' and a.matricola=p.matricola";
			ResultSet rs = connections.getStatement().executeQuery(qry);
			if (rs.next())
			{
				account=rs.getInt("tipologia");
				
				session=request.getSession(true);
				session.setAttribute("user", user);
				session.setAttribute("type", account);
				session.setAttribute("nome", rs.getString("nome"));
				session.setAttribute("cognome", rs.getString("cognome"));
				session.setAttribute("matricola", rs.getString("matricola"));
				session.setAttribute("tipologia", rs.getString("tipologia"));
				
				System.out.println("TIPOLOGIA: "+session.getAttribute("tipologia"));
				
				response.setContentType("text/html");
				ServletOutputStream out = response.getOutputStream();
				
				out.println("<html><head><body>");
				out.println("<script type=\"text/javascript\">");
				out.println("alert(\"Benvenuto "+user+"\",\"Accesso eseguito\")");
				out.println("</script>");
				out.println("</body></head></html>");
				
				System.out.println("benvenuto "+user);
				
				switch (account)
				{
				case 1: response.sendRedirect("adm/hadm.jsp"); break;
				case 2: response.sendRedirect("amm/hamm.jsp"); break;
				case 3: response.sendRedirect("dip/hdip.jsp"); break;
				}
				
			}
			else
			{
				session=request.getSession(true);
				session.invalidate();
				
				response.sendRedirect("loginerr.jsp");
			}
			
			rs.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
